# -*- coding: utf-8 -*-
import os
import sys
import uploader
import re
import urllib

class rich_text_converter:
    def __init__(self, home = os.getcwd()):
        self.home = home
        self.level = 0
        self.aPat = re.compile(r'(.*)<a href="(.+?)">(.*)')
        self.imgPat = re.compile(r'(.*)(<img.+?)src="(.+?)"(.*)')
        self.u = uploader.uploader()
        self.dirs = 0
        self.handled_a = 0
        self.handled_img = 0
        self.handled_html = 0

    def traverse(self, handler):
        self.__traverse(handler, self.home, 0)
        print "%d dirs, handled %d a, %d img, %d html" % (self.dirs, self.handled_a, self.handled_img, self.handled_html)

    def __traverse(self, handler, path, level):
        handler(level, path)
        for d in os.listdir(path):
            next_path = os.path.join(path, d)
            if os.path.isdir(next_path):
                self.__traverse(handler, next_path, level+1)
    
    def print_path(self, level, path):
        print '\t' * level + path 
    
    def handle_one_question(self, level, path):
        """
        traverse dir and modify original data in each dir as:
            exapand url in <a> as literal string
            upload pics and override original img src
            call tag file converter on answer.htm twice
                java -jar HtmlConverter.jar answer.htm ab  utf8
                java -jar HtmlConverter.jar answer.htm.a c  utf8
        """
        self.level = level

        print '  ' * self.level + path
        self.dirs += 1
        old_cwd = os.getcwd() 
        os.chdir(path)

        #try:
        #    os.remove("done")
        #except:
        #    pass
        #return

        if not os.path.exists("answer.htm") or os.path.exists("done"):
            return

        try:
            #self.expand_url_a(filename = "answer.htm", prefix = "a_")
            self.upload_pics(infilename = "answer.htm", prefix = "img_")
            self.handle_html(infilename = "img_answer.htm", prefix = "html_")
        except Exception, e:
            print e
            sys.exit()
        else:
            mark = open("done", "w")
            mark.write("done")
            mark.close()
        finally:
            os.chdir(old_cwd)
    
    def expand_url_a(self, filename, prefix):
        try:
            infile = open(filename, "r")
            outfilename = prefix + filename
            outfile = open(outfilename, "w")
        except Exception, e:
            print e
            sys.exit()

        outlines = []
        try:
            lines = infile.readlines()
            for line in lines:
                line = line.replace('</a>', '')
                outline = ''
                try:
                    elements = self.aPat.search(line).groups()
                except:
                    outline = line[:]
                else:
                    outline = "%s" %(elements[0],) + "&nbsp;" * 1 + "%s" %(elements[1],) + "&nbsp;" * 1 + "%s" %(elements[2], )
                if outline.endswith('\n') != True:
                    outline = outline + '\n'
                outlines.append(outline)
            outfile.writelines(outlines)
        except Exception, e:
            print e
            sys.exit()
        else:
            print '  ' * self.level + "a ok"
            self.handled_a += 1
        finally:
            outfile.close()
            infile.close()
            #sys.exit()
    
    def upload_pics(self, infilename, prefix):
        try:
            infile = open(infilename, "r")
            outfile = open(prefix+infilename, "w")
        except Exception, e:
            print e
            sys.exit()

        outlines = []
        try:
            lines = infile.readlines()
            for line in lines:
                outline = ''
                resultUrl = ''
                try:
                    elements = self.imgPat.search(line).groups()
                except:
                    outline = line[:]
                else:
                    # replace local file name with remote url
                    try:
                        localFileName = os.path.normpath(os.path.join(os.getcwd(), os.path.normcase(urllib.unquote(elements[2].decode("utf8").encode("cp936")))))
                        #print "upload",  localFileName
                        resultUrl = self.u.upload(localFileName)
                    except Exception, e:
                        print  e
                        raise e
                    else:
                        print "uploaded %s as %s" % (localFileName, resultUrl)
                        outline = '%s%ssrc="%s"%s' % (elements[0], elements[1], resultUrl, elements[3])
                if outline.endswith('\n') != True:
                    outline = outline + '\n'
                outlines.append(outline)
            outfile.writelines(outlines)
        except Exception, e:
            print e
            sys.exit()
        else:
            print '  ' * self.level + "img ok"
            self.handled_img += 1
        finally:
            infile.close()
            outfile.close()
            # sys.exit()
    
    def handle_html(self, prefix, infilename):
        try:
            cmd = r"java -jar E:\autoQA\code\rich_text\import\HtmlConverter.jar %s ab utf8" % (infilename,) 
            #print cmd
            os.system(cmd)

            cmd = r"java -jar E:\autoQA\code\rich_text\import\HtmlConverter.jar %s.a c utf8" % (infilename,) 
            #print cmd
            os.system(cmd)

            cmd = r"copy /Y %s %s" %(infilename + ".a.c", prefix+infilename)
            #print cmd
            os.system(cmd)

            cmd = r"copy /Y %s %s" %(infilename + ".b", "plain_answer.txt")
            #print cmd
            os.system(cmd)

        except Exception, e:
            print e
            sys.exit()
        else:
            print '  ' * self.level + "html ok"
            self.handled_html += 1
            #sys.exit()

if __name__ == "__main__":
    if len(sys.argv[1:]) < 1:
        print "Usage: %s <start_dir>" %(sys.argv[0], )
        sys.exit()

    conv = rich_text_converter(sys.argv[1])
    conv.traverse(handler = conv.handle_one_question)
